// from 'background'
chrome.action.onClicked.addListener(function (tab) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, { from: 'background', to: 'popupBox', type: 'switchPopup', data: 'toggle' });
  });
});

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.to === 'background') {
    if (msg.type === 'fetchData' && msg.data) {
      const { url, ...options } = msg.data;
      fetch(url, options).then(res => res.json())
        .then(result => { sendResponse(result); })
        .catch(error => {
          sendResponse(error);
        });
      // return true;
    }
    if (msg.type === 'updateConfig' && msg.data && msg.data.hasOwnProperty('isGlobalOpen')) {
      const path = {};
      const suffix = msg.data.isGlobalOpen ? '_run.png' : '_stop.png';
      [16, 24, 36, 128].forEach(item => {
        path[item] = `/logos/${item + suffix}`;
      });
      chrome.action.setIcon({ path });
    }
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      const oMsg = { ...msg, from: 'background' };
      oMsg.to = msg.type === 'switchPopup' ? 'popupBox' : 'content';
      chrome.tabs.sendMessage(tabs[0].id, oMsg);
    })
  }
});

chrome.storage.local.get(['isGlobalOpen'], (result) => {
  chrome.action.setIcon({ path: result.isGlobalOpen ? "/logos/16_run.png" : "/logos/16_stop.png" });
});